import updateManager from './common/updateManager';
import {
  users
} from './tools/users'
import {
  ui
} from './tools/ui'

App({
  globalData: {
    cloudPrefix: "cloud://wjs-4gpwpq5j4372152f.776a-wjs-4gpwpq5j4372152f-1314549356",
    shareTicket: '',
    openGId: ''
  },
  onLaunch: function () {},
  onShow: function (options) {
    updateManager();

    if (options?.path.endsWith("/obtain")) return

    if (options && options.scene == 1044) {
      this.globalData.shareTicket = options.shareTicket
      this.getShareTiket().then(res => {
        // console.log(res)
        if (!res?.errMsg?.endsWith(":ok")) return

        this.globalData.openGid = res.result.data.openGId
        this.gotoCoupon(res.result.data.openGId)
      })
    }
  },
  gotoCoupon(openGId) {
    users.getUser().then(user => {
      if (user.role != 'admin') return

      ui.confirmx('检测到群分享，是否创建群优惠券？')
        .then(yes => {
          if (!yes) return
          wx.navigateTo({
            url: `/pages/usercenter/coupon/edit/couponEdit?openGId=${openGId}`,
          })
        })
    })
  },
  getShareTiket: function () {
    const that = this
    return new Promise((resolve, reject) => {
      if (!that.globalData.shareTicket) {
        resolve(null)
        return
      }
      this.getShareInfo(resolve, reject)
    })
  },
  getShareInfo(resolve, reject) {
    const that = this
    wx.getShareInfo({
      shareTicket: that.globalData.shareTicket,
      success: function (res) {
        // console.log('wx.getShareInfo.success::', JSON.stringify(res))
        let js_encryptedData = res.encryptedData
        let js_iv = res.iv
        wx.login({
          success: function (res) {
            let js_code = res.code
            // console.log('wx.login.success::', js_code)

            wx.cloud.callFunction({
              name: 'token',
              data: {
                js_code: res.code,
                encryptedData: js_encryptedData,
                iv: js_iv
              },
              success: function (res) {
                resolve(res)
              },
              fail: function (err) {
                reject(res)
              }
            })
          },
          fail: function (res) {
            reject(res)
          }
        })
      }
    })
  }
});